<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ifast - 文件管理器</title>
<meta name="keywords" content="">
<meta name="description" content="">
<link rel="shortcut icon" href="favicon.ico">
<link href="/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
<link href="/css/font-awesome.css?v=4.4.0" rel="stylesheet">
<link href="/css/animate.css" rel="stylesheet">
<link href="/js/plugins/layui_2_5_4/css/layui.css" rel="stylesheet">
<link href="/css/style.css?v=4.1.0" rel="stylesheet">
<link href="/js/plugins/zTree_v3/css/metroStyle/metroStyle.css"
	rel="stylesheet">

</head>
<body class="gray-bg">
	<div class="wrapper wrapper-content" id="app">
		<div class="row">
			<div class="col-sm-3">
				<div class="ibox float-e-margins">
					<div class="ibox-content">
<!-- 						<div class="file-manager"> -->

<!-- 							<div class="hr-line-dashed"></div> -->
<!-- 							<ul id="showMsg" class="folder-list" style="padding: 0"></ul> -->
<!-- 							<div class="demo-tree demo-tree-box" -->
<!-- 								style="height: 400px; overflow: scroll;"> -->
<!-- 								<ul id="departtree" class="ztree"></ul> -->
<!-- 							</div> -->
<!-- 						</div> -->
						<div class="layui-card-body">  
				           	<ul class="gmlist">
				           		<li id="showMsg" class="folder-list" style="padding: 0"></li>
				           		<li id="departtree" class="ztree"></li>
				           	</ul>
						</div>
					</div>
				</div>
			</div>
			<div class="columns pull-left">
<!-- 				<button shiro:hasPermission="sys:user:add" type="button" -->
<!-- 					class="btn  btn-primary" onclick="add()"> -->
<!-- 					<i class="fa fa-plus hidden" aria-hidden="true"></i>添加 -->
<!-- 				</button> --> 
			</div> 
			<div class="demoTable" style="padding-left:10px">
				<button  type="button" class="btn  btn-primary" onclick="add()">
					<i class="fa fa-plus hidden" aria-hidden="true"></i>添加
				</button>
				<span style="padding-left: 10px">姓名：</span>
				<div class="layui-inline">
					
					<input class="layui-input" name="name" id="nameReload" autocomplete="off"> 
				</div>
<!-- 				手机号： -->
<!-- 				<div class="layui-inline"> -->
<!-- 					<input class="layui-input" name="mobile" id="mobileReload" autocomplete="off"> -->
<!-- 				</div> -->
				
				<button class="layui-btn" data-type="reload">搜索</button>
			</div>
			<div class="col-sm-9 animated fadeInRight">
				 
					<table id="demo" class="layui-hide" lay-filter="demo"></table>
				 
			</div>
		</div>
	</div>

	<!-- 全局js -->
	<script src="/js/jquery.min.js"></script>
	<script src="/js/plugins/layui_2_5_4/layui.all.js"></script>
	<script src="/js/plugins/layui_2_5_4/lay/modules/layer.js"></script>
	<script src="/js/plugins/zTree_v3/js/jquery.ztree.all.js"></script>
	<script src="/js/plugins/zTree_v3/js/jquery.ztree.core.js"></script>
	<script src="/js/plugins/zTree_v3/js/jquery.ztree.exedit.min.js"></script>
 	<script src="/js/plugins/zTree_v3/js/jquery.ztree.excheck.min.js"></script>
	<script type="text/html" id="barDemo"> 
  		<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
		<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">修改密码</a>
	</script>
<script type="text/javascript">
		var canEnable = false; 
</script>
<div shiro:hasPermission="system:sysDept:add">
	<script type="text/javascript">
		canEnable = true; 
	</script>
</div>

<script th:inline="javascript">

var detpId = [[${deptId}]] == '' ? '' : [[${deptId}]];

function add() {
	if(detpId == ""){
        layer.msg("请先选择单位!");
        return;
	}
	// iframe层
	layer.open({
		type : 2,
		title : '增加用户',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '800px', '520px' ],
		content : '/sys/user/add/' + detpId
	});
}
function remove(id) {
	layer.confirm('确定要删除选中的记录？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$.ajax({
			url : "/sys/user/remove",
			type : "post",
			data : {
				'id' : id
			},
			success : function(r) {
				if (r.code == 0) {
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	})
}
function edit(id) {
	layer.open({
		type : 2,
		title : '用户修改',
		maxmin : true,
		shadeClose : false,
		area : [ '800px', '520px' ],
		content : '/sys/user/edit/' + id // iframe的url
	});
}
function resetPwd(id) {
	layer.open({
		type : 2,
		title : '重置密码',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '400px', '260px' ],
		content : '/sys/user/resetPwd/' + id // iframe的url
	});
}
function reLoad(){
	var nameReload = $('#nameReload');  
    layui.use('table', function(){
    	var table = layui.table;
      	table.reload('testReload', {
	        page: {
	          curr: 1 //重新从第 1 页开始
	        },
	        where: { 
	        	name: nameReload.val(),
	        //	mobile: mobileReload.val(),
	        	deptId:detpId 
        	}
      	}, 'data');
	});
}

layui.use('table', function(){
	var table = layui.table;
   
	//监听工具条
	table.on('tool(demo)', function(obj){
		var data = obj.data;
     	if(obj.event === 'detail'){
    		resetPwd(data.id);
     	} else if(obj.event === 'del'){
    		remove(data.id); 
     	} else if(obj.event === 'edit'){
    		edit(data.id);
     	}
	});

  
  //直接赋值数据
  	table.render({
    	elem: '#demo'
    	,id: 'testReload'
    	//,width: 900
    	//,height: 274
    	// ,toolbar: true
    	,cellMinWidth: 80 //全局定义常规单元格的最小宽度
    	,url:'/sys/user/list'
    	,cols: [[
//              {type: 'checkbox', fixed: 'left'}
             {field:'id', title:'ID', fixed: 'left',align: 'center'}
             ,{field:'username', title:'登录名',align: 'center'}
             ,{field:'name', title:'姓名',  align: 'center'}
             ,{field:'status', title:'状态',align: 'center', templet: function(res){
                 var status = res.status == 1 ? '正常':'禁用';
            	 return '<em>'+ status +'</em>'
             }} 
             ,{fixed: 'right', title:'操作',align: 'center', toolbar: '#barDemo', }
           ]]
  		,skin: 'row' //表格风格
    	,even: true
    	//,size: 'lg' //尺寸
    
    	,page: true //是否显示分页
    	,limits: [3,5,10]
    	,limit: 10 //每页默认显示的数量 
	    //,loading: false //请求数据时，是否显示loading
    	,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
        	return {
          		"code": res.code, //解析接口状态
          		"msg": res.msg, //解析提示文本
          		"count": res.data.total, //解析数据长度
          		"data": res.data.records //解析数据列表
        	};
         }
	});
 
	var $ = layui.$, active = {
		reload: function(){
	    	var nameReload = $('#nameReload');
	     // var mobileReload = $('#mobileReload');
	      
	      //执行重载
	      	table.reload('testReload', {
		      	page: {
		        	curr: 1 //重新从第 1 页开始
		        },
		        where: { 
		        	name: nameReload.val(),
		        //	mobile: mobileReload.val(),
		        	deptId:detpId 
		        }
	      	}, 'data');
		}
	};
	  
  	$('.demoTable .layui-btn').on('click', function(){
    	var type = $(this).data('type');
    	active[type] ? active[type].call(this) : '';
  	}); 
});
</script>
<script type="text/javascript">
		
		var setting = {
			showLine : true,
			edit: {
                enable: canEnable,
                editNameSelectAll: true,// 节点编辑名称 input 初次显示时,设置 txt 内容是否为全选状态。
    			removeTitle:"删除",		// 删除按钮的 Title 辅助信息
    			renameTitle:"编辑"		// 编辑名称按钮的 Title 辅助信息。 
            },
            view: {
                addHoverDom: canEnable ? addHoverDom:null,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
			async: {
				enable: true,
				url:"/sys/dept/zTreeByPid",
				autoParam:["id", "name=name"],
				otherParam:{"otherParam":"zTreeAsyncTest"},
				dataFilter: filter
			},
            data: {
                simpleData: {
                	enable : true,
    				idKey : "id",		// 结点的id,对应到Json中的id
    				pIdKey : "pId",// 结点的pId,对应到Json中的pId
                }
            },
            callback : {
    			beforeEditName: beforeEditName,	// 用于捕获节点编辑按钮的 click 事件，并且根据返回值确定是否允许进入名称编辑状态
    			beforeRemove: beforeRemove,		// 用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
    			beforeRename: beforeRename,		// 用于捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）之后，更新节点名称数据之前的事件回调函数，并且根据返回值确定是否允许更改名称的操作
    			onClick : showDetail			// 	点击节点时，显示节点详细信息
    		},

		};

		function filter(treeId, parentNode, childNodes) {
			if (!childNodes) return null;
			for (var i=0, l=childNodes.length; i<l; i++) {
				childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
			}
			return childNodes;
		}
		
		var treeNodes;
		$.ajax({
             async : false,
             cache:false,
             type: 'POST',
             dataType : "json",
             url: "/sys/dept/zTree",
             error: function () {//请求失败处理函数
                 alert('请求失败');
             },
             success:function(data){ //请求成功后处理函数。
              	treeNodes = eval(data); //把后台封装好的简单Json格式赋给treeNodes
             }
         });
     

		$(document).ready(function(){
			$.fn.zTree.init($("#departtree"), setting,treeNodes);
		});
		
        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_"+treeNode.tId).unbind().remove();
        };
        
        
        var log, className = "dark";

        var rootNum=0;
        // 添加根目录。界面上添加一个button，点击时执行。（因为，树上直接进行添加操作，添加的是子部门）
        function addRootDep(){
        	rootNum++;
        	$.ajax({
        		type : "POST",  
        	    async : false,  
        	    url : "department!addDepNote.action",  
        	    data :  
        	    {  
        	    	departName : "根部门" + rootNum,
        	    	parentId:0
        	    },
        	    success:function(result){
        	    	if(""!=result ){
        	    		var zTree = $.fn.zTree.getZTreeObj("departtree");
        	    		var newNode=[{id:result,departName:"根部门"+rootNum,parentId:0}];
        	    		zTree.addNodes(null,newNode);
        	    	}else{
        	    		alert("无法添加根部门，请联系管理员！");
        	    	}
        	    }
        	}); 		
        } 
        
        // 删除操作
        function beforeRemove(treeId, treeNode) {
        	className = (className === "dark" ? "":"dark");
        	var zTree = $.fn.zTree.getZTreeObj("departtree");
        	zTree.selectNode(treeNode);
        	
        	var isDeled=false;
        	 
      		$.ajax({
      			type : "POST",  
      		    async : false,  
      		    url : "/sys/dept/remove",  
      		    data :  
      		    {  
      		    	id : treeNode.id  
      		    },
      		    success:function(result){
      		    	if (result.code == "0") {
      		    		isDeled= true;
      				} else {
      					layer.tips('删除失败.'+result.msg, '#showMsg', {
              			  	tips: [4, '#78BA32']
              			});
      					isDeled= false;
      				}
      		    }
      		}); 
      		
        	return isDeled;
        	 
        }
     	// 在进行重命名之前，进行一下确认
        function beforeEditName(treeId, treeNode) {
        	className = (className === "dark" ? "":"dark");
        	var zTree = $.fn.zTree.getZTreeObj("departtree");
        	zTree.selectNode(treeNode);
        	//return  layer.confirm("确认要重命名部门 -- " + treeNode.name + " 吗？");
        }
        // 重命名操作
        function beforeRename(treeId, treeNode, newName, isCancel) {
        	className = (className === "dark" ? "":"dark");
        	if (newName.length == 0) {
        		layer.tips('节点名称不能为空.', '#showMsg', {
        			  tips: [4, '#78BA32']
        		}); 
        		var zTree = $.fn.zTree.getZTreeObj("departtree");
        		setTimeout(function(){zTree.editName(treeNode)}, 10);
        		return false;
        	}else{
        		var isDeled=false;
        		$.ajax({
        			type : "POST",  
        		    async : false,  
        		    url : "/sys/dept/zTreeEditNameById",  
        		    data :  
        		    {  
        		    	id : treeNode.id,
        		    	name : newName
        		    },
        		    success:function(result){
        		    	if (result.code == "0") {
        		    		isDeled= true;
        				} else {
        					layer.tips('修改失败.', '#showMsg', {
        	        			  tips: [4, '#78BA32']
        	        		});
        					isDeled= false;
        				}
        		    }
        		}); 			
        		return isDeled;
        	}
        }

        // 添加子部门操作
        var newCount = Date.now();
        function addHoverDom(treeId, treeNode) {
        	var sObj = $("#" + treeNode.tId + "_span");
        	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        		+ "' title='添加' onfocus='this.blur();'></span>";
        	sObj.after(addStr);
        	var btn = $("#addBtn_"+treeNode.tId); 
        	//var isAdded=false;
        	if (btn) btn.bind("click", function(){
        		newCount = Date.now();
        		$.ajax({
        			type : "POST",  
        		    async : false,  
        		    url : "/sys/dept/save",  
        		    data :  
        		    {  
        		    	name : "新部门" + newCount,
        		    	parentId:treeNode.id
        		    },
        		    success:function(result){
        		    	console.log(result); 
        		    	if(result.code == 0){
//         		    		var zTree = $.fn.zTree.getZTreeObj("departtree");
//         		    		zTree.reAsyncChildNodes(treeNode, "refresh");
        		    		var zTree = $.fn.zTree.getZTreeObj("departtree");
							zTree.addNodes(treeNode, {id:result.data, parentId:treeNode.id, name:"新分类" + newCount});
				 			return false;
        		    	}else{
        		    		layer.tips('"无法添加新部门，请联系管理员！', '#showMsg', {
      	        			  	tips: [4, '#78BA32']
      	        			});  
        		    	}
        		    }
        		});	
        		return false;			
        	});
        };  
        
        function showDetail(event, treeId, treeNode, clickFlag){
        	detpId = treeNode.id;
        	reLoad();
        }
	</script>
</body>
</html>
